package logic

import (
	"context"
	"github.com/pkg/errors"
	"mall/app/product/cmd/rpc/pb"
	"mall/common/xerr"
	"sort"

	"mall/app/product/cmd/api/internal/svc"
	"mall/app/product/cmd/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCategoryListWithTreeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCategoryListWithTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCategoryListWithTreeLogic {
	return &GetCategoryListWithTreeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCategoryListWithTreeLogic) GetCategoryListWithTree() (*types.CategoryWithTreeResp, error) {
	resp := &types.CategoryWithTreeResp{}
	res, err := l.svcCtx.ProductRpc.GetCategoryList(l.ctx, &pb.EmptyReq{})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrorWithMsg("获取失败"), "err: %v", err)
	}
	// 获取Level1
	var level1List []types.CategoryWithTree
	for _, v := range res.List {
		if v.ParentCid == 0 {
			level1List = append(level1List, types.CategoryWithTree{
				CatId:        v.CatId,
				Name:         v.Name,
				ParentCid:    v.ParentCid,
				CatLevel:     v.CatLevel,
				ShowStatus:   v.ShowStatus,
				Sort:         v.Sort,
				Icon:         v.Icon,
				ProductUnit:  v.ProductUnit,
				ProductCount: v.ProductCount,
				Children:     getChildren(v, res.List),
			})
		}
	}
	sort.Slice(level1List, func(i, j int) bool {
		if level1List[i].Sort > level1List[j].Sort {
			return false
		}
		return true
	})
	resp.Data = level1List
	return resp, nil
}

func getChildren(root *pb.CategoryEntity, all []*pb.CategoryEntity) []types.CategoryWithTree {
	var level []types.CategoryWithTree
	for _, v := range all {
		if v.ParentCid == root.CatId {
			level = append(level, types.CategoryWithTree{
				CatId:        v.CatId,
				Name:         v.Name,
				ParentCid:    v.ParentCid,
				CatLevel:     v.CatLevel,
				ShowStatus:   v.ShowStatus,
				Sort:         v.Sort,
				Icon:         v.Icon,
				ProductUnit:  v.ProductUnit,
				ProductCount: v.ProductCount,
				Children:     getChildren(v, all),
			})
		}
	}
	sort.Slice(level, func(i, j int) bool {
		if level[i].Sort > level[j].Sort {
			return false
		}
		return true
	})
	return level
}
